<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { RouteMap, useRouter } from '@/router';
import { useUserStore } from '@/store/user';
import * as UserService from '../../api/user';
import { COUNTRIES_LIST } from '@/constants/countries';
import { useLocale } from '@/locale/locale';
import { isWechat } from '@/utils/platform';

const { t } = useLocale();
const userStore = useUserStore();
const router = useRouter();
const type = ref('');
const firstName = ref('');
const lastName = ref('');
const email = ref('');
const phoneArea = ref('');
const phone = ref('');
const emailCodeText = ref(t('LLKey_sendCode'));
const isEmailSending = ref(false);
const emailCountDown = ref(0);
const phoneCodeText = ref(t('LLKey_sendCode'));
const isPhoneSending = ref(false);
const phoneCountDown = ref(0);
const emailCode = ref('');
const phoneCode = ref('');
const countryIndex = ref(0);

onLoad(async (options) => {
  type.value = options!.type;
});

onMounted(async () => {
  firstName.value = userStore.user.firstName;
  lastName.value = userStore.user.lastName;
  phone.value = userStore.user.phoneNumber;
  email.value = userStore.user.email;
  phoneArea.value = userStore.user.countryCode;
  countryIndex.value = COUNTRIES_LIST.findIndex((item) => item.code === userStore.user.countryCode);
});

async function getEmailCode() {
  if (isEmailSending.value) {
    return false;
  } else {
    isEmailSending.value = true;
    const res = await UserService.sendEmailCode(email.value);
    if (res.code == 0) {
      setTimeout(() => {
        emailCountDown.value = 60;
        emailCodeText.value = `${emailCountDown.value}s`;
        const timer = setInterval(() => {
          emailCountDown.value -= 1;
          if (emailCountDown.value <= 0) {
            clearInterval(timer);
            isEmailSending.value = false;
            emailCodeText.value = t('LLKey_sendCode');
          } else {
            emailCodeText.value = `${emailCountDown.value}s`;
          }
        }, 1000);
      });
    } else {
      // res.message
      uni.showToast({
        title: res.message,
        icon: 'none'
      });
      isEmailSending.value = false;
      return;
    }
  }
}

const changePhoneArea = (e: string) => {
  phoneArea.value = e;
};

defineExpose({
  changePhoneArea
});

async function getPhoneCode() {
  if (isPhoneSending.value) {
    return false;
  } else {
    isPhoneSending.value = true;
    const res = await UserService.sendPhoneCode(phoneArea.value, phone.value);
    if (res.code == 0) {
      setTimeout(() => {
        phoneCountDown.value = 60;
        phoneCodeText.value = `${phoneCountDown.value}s`;
        const timer = setInterval(() => {
          phoneCountDown.value -= 1;
          if (phoneCountDown.value <= 0) {
            clearInterval(timer);
            isPhoneSending.value = false;
            phoneCodeText.value = t('LLKey_sendCode');
          } else {
            phoneCodeText.value = `${phoneCountDown.value}s`;
          }
        }, 1000);
      });
    } else {
      // res.message
      uni.showToast({
        title: res.message,
        icon: 'none'
      });
      isPhoneSending.value = false;
      return;
    }
  }
}

async function saveSet() {
  if (type.value == 'name') {
    const res = await UserService.setUserInfo({
      first_name: firstName.value,
      last_name: lastName.value
    });
    if (res.code == 0) {
      userStore.setFirstName(firstName.value);
      userStore.setLastName(lastName.value);
      userStore.setFullName(firstName.value + ' ' + lastName.value);
      uni.navigateBack();
    } else {
      // res.message
      uni.showToast({
        title: res.message,
        icon: 'none'
      });
      return;
    }
  } else if (type.value == 'email') {
    const res = await UserService.bindEmail({
      email: email.value,
      code: emailCode.value
    });
    if (res.code == 0) {
      userStore.setEmail(email.value);
      uni.navigateBack();
    } else {
      // res.message
      uni.showToast({
        title: res.message,
        icon: 'none'
      });
      return;
    }
  } else if (type.value == 'phone') {
    const res = await UserService.bindPhone({
      AreaNo: phoneArea.value,
      Phone: phone.value,
      Code: phoneCode.value
    });
    if (res.code == 0) {
      userStore.setCountryCode(phoneArea.value);
      userStore.setPhoneNumber(phone.value);
      uni.navigateBack();
    } else {
      // res.message
      uni.showToast({
        title: res.message,
        icon: 'none'
      });
      return;
    }
  }
}
</script>

<template>
  <uni-nav-bar
    v-if="isWechat()"
    :border="false"
    :title="
      type == 'name'
        ? t('LUKey_nicknameSetting')
        : type == 'email'
          ? t('LUKey_emailSetting')
          : t('LUKey_mobileSetting')
    "
    fixed
    left-icon="left"
    status-bar
    @click-left="router.back"
  ></uni-nav-bar>
  <view class="account-set-contain">
    <view v-if="type == 'name'" class="account-set-view">
      <view class="account-set-view-item">
        <view class="account-set-view-item-title">{{ t('LCKey_firstName') }}</view>
        <view class="account-set-view-item-input">
          <input
            v-model="firstName"
            :placeholder="t('LCKey_inputFirstName')"
            placeholder-class="placeholder"
          />
        </view>
      </view>
      <view class="account-set-view-item">
        <view class="account-set-view-item-title">{{ t('LCKey_lastName') }}</view>
        <view class="account-set-view-item-input">
          <input
            v-model="lastName"
            :placeholder="t('LCKey_inputLastName')"
            placeholder-class="placeholder"
          />
        </view>
      </view>
      <view class="account-set-view-tips">{{ t('LUKey_inputPinyin') }}</view>
    </view>

    <view v-if="type == 'email'" class="account-set-view">
      <view class="account-set-view-item">
        <view class="account-set-view-item-title">{{ t('LUKey_emailAddress') }}</view>
        <view class="account-set-view-item-input">
          <input
            v-model="email"
            :placeholder="t('LUKey_inputEmailAddress')"
            placeholder-class="placeholder"
            type="email"
          />
        </view>
      </view>
      <view class="account-set-view-item">
        <view class="account-set-view-item-title">{{ t('LKey_normalVerificationCode') }}</view>
        <view class="account-set-view-item-input">
          <input
            v-model="emailCode"
            :placeholder="t('LLKey_codePlaceholder')"
            placeholder-class="placeholder"
            type="number"
          />
          <view class="account-set-view-item-code" @click="getEmailCode">
            <text>{{ emailCodeText }}</text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="type == 'phone'" class="account-set-view">
      <view class="account-set-view-item">
        <view class="account-set-view-item-title">{{ t('LUKey_mobile') }}</view>
        <view class="account-set-view-item-mobile">
          <view
            class="account-set-view-item-mobile-value"
            @click="router.to(RouteMap.countries, { type: 'intentionPhoneArea', code: phoneArea })"
          >
            <view>
              {{ phoneArea }}
            </view>
            <image src="/static/icon_account_arrow_down.png" />
          </view>
          <input
            v-model="phone"
            :placeholder="t('LUKey_inputMobile')"
            placeholder-class="placeholder"
            type="tel"
          />
        </view>
      </view>
      <view class="account-set-view-item">
        <view class="account-set-view-item-title">{{ t('LKey_normalVerificationCode') }}</view>
        <view class="account-set-view-item-input">
          <input
            v-model="phoneCode"
            :placeholder="t('LLKey_codePlaceholder')"
            placeholder-class="placeholder"
            type="number"
          />
          <view class="account-set-view-item-code" @click="getPhoneCode">
            <text>{{ phoneCodeText }}</text>
          </view>
        </view>
      </view>
    </view>
    <view class="account-set-save" @click="saveSet">{{ t('LCKey_save') }}</view>
  </view>
</template>

<style lang="scss" scoped>
.account-set {
  &-contain {
    padding-top: 20rpx;
  }

  &-view {
    background: #ffffff;
    border-radius: 20rpx;
    padding: 8rpx 32rpx 30rpx;

    &-item {
      border-bottom: 1px solid #f4f4f4;
      //padding: 32rpx 0;
      display: flex;
      align-items: center;

      &-title {
        padding: 32rpx 0;
        width: 212rpx;
        font-size: 28rpx;
        color: #3d3d3d;
        font-weight: 500;
        line-height: 40rpx;
      }

      &-mobile {
        flex: 1;
        display: flex;
        align-items: center;

        &-value {
          display: flex;
          align-items: center;

          view {
            font-size: 28rpx;
            color: #3d3d3d;
            font-weight: 400;
            line-height: 40rpx;
            margin-right: 2rpx;
          }

          image {
            display: block;
            width: 32rpx;
            height: 32rpx;
          }
        }

        input {
          margin-left: 20rpx;
          flex: 1;
          font-size: 28rpx;
          color: #3d3d3d;
          font-weight: 400;
          line-height: 40rpx;
          height: 104rpx;

          &.placeholder {
            color: #adaeb0;
          }
        }
      }

      &-input {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 104rpx;

        input {
          font-size: 28rpx;
          color: #3d3d3d;
          font-weight: 400;
          line-height: 40rpx;
          height: 104rpx;

          &.placeholder {
            color: #adaeb0;
          }
        }
      }

      &-code {
        width: 200rpx;
        text-align: right;
        text {
          font-size: 28rpx;
          color: #df7c32;
          line-height: 40rpx;
          font-weight: 400;
          text-align: right;
        }
      }
    }

    &-tips {
      padding: 18rpx;
      font-size: 24rpx;
      color: #d13820;
      line-height: 34rpx;
      font-weight: 400;
    }
  }

  &-save {
    margin: 46rpx 32rpx;
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    font-size: 32rpx;
    color: #ffffff;
    font-weight: 500;
    background: #269c74;
    border-radius: 100rpx;
  }
}
</style>
